<template>
  <div class="category-manager">
    <!-- 页面标题区域 -->
    <div class="page-header">
      <h2>分类管理</h2>
      <el-tag type="info">共 {{ total }} 个分类</el-tag>
    </div>

    <!-- 搜索和操作区域 -->
    <el-card class="operation-area" shadow="hover">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="分类名称">
          <el-input v-model="searchForm.name" placeholder="请输入分类名称" clearable></el-input>
        </el-form-item>
        <el-form-item>
          <el-button size="medium" plain type="primary" @click="handleSearch">查询</el-button>
          <el-button size="medium" plain @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
      <div class="operation-buttons">
        <!-- 按钮图标使用组件形式 -->
        <el-button plain size="medium" type="primary" class="add-button" @click="handleAdd">
          <Plus />新增分类
        </el-button>
        <el-button plain size="medium" @click="getList">
          <Refresh />刷新
        </el-button>
      </div>
    </el-card>

    <!-- 分类列表 -->
    <el-card class="table-card" shadow="hover">
      <el-table :data="categories" border style="width: 100%">
        <el-table-column prop="id" label="ID" width="80"></el-table-column>
        <el-table-column label="图标" width="100">
          <template #default="scope">
            <!-- 1. 列表图标：使用 component 组件渲染 -->
            <component
                :is="getIconComponent(scope.row.icon)"
                style="font-size: 16px;width: 16px;text-align: center !important;height: 16px;"
            ></component>
          </template>
        </el-table-column>
        <el-table-column prop="name" label="分类名称"></el-table-column>
        <el-table-column prop="description" label="描述" show-overflow-tooltip></el-table-column>
        <el-table-column prop="createdAt" label="创建时间" width="180"></el-table-column>
        <el-table-column label="操作" width="150" fixed="right">
          <template #default="scope">
            <!-- 操作按钮图标使用组件形式 -->
            <el-button type="text" size="small" @click="handleEdit(scope.row)">
              <Edit />编辑
            </el-button>
            <el-button type="text" size="small" class="delete-btn" @click="handleDelete(scope.row)">
              <Delete />删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <pagination v-show="total > 0" :total="total" :page.sync="queryParams.currentPage" :limit.sync="queryParams.size" @pagination="getList" />
    </el-card>

    <!-- 分类表单对话框 -->
    <el-dialog :title="dialogTitle" v-model="dialogVisible" width="500px">
      <el-form :model="form" :rules="rules" ref="formRef" label-width="100px">
        <el-form-item label="分类名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入分类名称"></el-input>
        </el-form-item>
        <el-form-item label="图标" :label-width="formLabelWidth" prop="icon">
          <el-select v-model="form.icon" filterable placeholder="请选择图标">
            <el-option v-for="dict in iconDict" :key="dict.itemKey" :label="dict.itemKey" :value="dict.itemValue">
              <!-- 2. 下拉框图标：使用 component 组件渲染 -->
              <component
                  :is="getIconComponent(dict.itemValue)"
                  style="font-size: 14px; margin-right: 8px;width: 16px;"
              ></component>
              {{ dict.itemKey }}
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input type="textarea" v-model="form.description" :rows="4" placeholder="请输入分类描述"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, getCurrentInstance } from 'vue'
import { toast } from 'vue3-toastify'
import 'vue3-toastify/dist/index.css'
import Request from '@/utils/request'
import Pagination from '@/components/Pagination/index.vue'



// 获取当前实例以访问 $confirm 方法
const instance = getCurrentInstance()

// 搜索表单
const searchForm = reactive({
  name: ''
})

// 查询参数
const queryParams = reactive({
  currentPage: 1,
  size: 10
})

// 分类列表
const categories = ref([])
const total = ref(0)

// 对话框状态
const dialogVisible = ref(false)
const dialogTitle = ref('')

// 表单数据和验证
const formRef = ref(null)
const form = reactive({
  id: undefined,
  name: '',
  icon: '', // 存储图标名称（如 "Folder"、"Tag"）
  description: ''
})

const rules = ref({
  name: [
    { required: true, message: '请输入分类名称', trigger: 'blur' }
  ],
  icon: [
    { required: true, message: '请选择图标', trigger: 'change' }
  ]
})

// 表单标签宽度
const formLabelWidth = '100px'

// 图标字典
const iconDict = ref([])

// 获取图标组件（核心方法：将图标名称转换为组件）
const getIconComponent = (iconName) => {
  return iconName
}

// 页面加载时获取分类列表
onMounted(() => {
  getList()
})

// 获取分类列表
const getList = async () => {
  try {
    const params = {
      ...queryParams,
      name: searchForm.name
    }
    const res = await Request.get('/category/page', { params })
    if (res.code === '0') {
      // 格式化日期
      categories.value = res.data.records.map(item => ({
        ...item,
        createdAt: new Date(item.createdAt).toLocaleString('zh-CN', {
          year: 'numeric',
          month: '2-digit',
          day: '2-digit',
          hour: '2-digit',
          minute: '2-digit',
          second: '2-digit',
          hour12: false
        }).replace(/\//g, '-')
      }))
      total.value = res.data.total
    }
  } catch (error) {
    console.error('获取分类列表失败:', error)
    toast.error('获取分类列表失败')
  }
}

// 搜索
const handleSearch = () => {
  queryParams.currentPage = 1
  getList()
}

// 重置搜索
const resetSearch = () => {
  searchForm.name = ''
  handleSearch()
}

// 新增分类
const handleAdd = () => {
  dialogTitle.value = '新增分类'
  // 重置表单
  form.id = undefined
  form.name = ''
  form.icon = ''
  form.description = ''
  loadIconList()
  dialogVisible.value = true
}

// 编辑分类
const handleEdit = (row) => {
  dialogTitle.value = '编辑分类'
  // 复制行数据到表单
  form.id = row.id
  form.name = row.name
  form.icon = row.icon
  form.description = row.description
  loadIconList()
  dialogVisible.value = true
}

// 删除分类
const handleDelete = async (row) => {
  try {
    await instance.proxy.$confirm({
      message: '确认删除该分类?',
      title: '删除确认',
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning'
    })

    const res = await Request.delete(`/category/${row.id}`)
    if (res.code === '0') {
      toast.success('删除成功')
      getList()
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除分类失败:', error)
      toast.error('删除失败')
    }
  }
}

// 提交表单
const submitForm = async () => {
  try {
    const valid = await formRef.value.validate()
    if (valid) {
      const method = form.id ? 'put' : 'post'
      const url = form.id ? `/category/${form.id}` : '/category'
      const res = await Request[method](url, { ...form })

      if (res.code === '0') {
        toast.success(`${form.id ? '更新' : '添加'}成功`)
        dialogVisible.value = false
        getList()
      }
    }
  } catch (error) {
    if (error.name !== 'ValidationError') {
      console.error('提交失败:', error)
      toast.error('提交失败')
    }
  }
}

// 加载图标列表（确保后端返回的是图标名称，如 "Folder" 而非 "el-icon-folder"）
const loadIconList = async () => {
  try {
    const res = await Request.get("/dictitem/findByType", {
      params: { code: "icon" }
    })
    if (res.code === '0') {
      // 假设后端返回格式：[{itemKey: "文件夹", itemValue: "Folder"}, ...]
      iconDict.value = res.data
    } else {
      toast.error('获取图标列表失败')
    }
  } catch (error) {
    console.error('获取图标列表失败:', error)
    toast.error('获取图标列表失败')
  }
}
</script>

<style scoped>
/* 保持原有样式不变，新增图标相关样式 */
/* 图标大小统一控制 */
:deep(.el-icon) {
  font-size: 16px;
}



/* 下拉框选项中的图标与文字间距 */
:deep(.el-select-dropdown__item) {
  display: flex;
  align-items: center;
}
</style>
